package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private IScheduleClient scheduleClient;

    /**
     * 添加文章到任务中
     * @param wmNews
     */
    @Override
    public void addWmNewsToTask(WmNews wmNews) {

        Task task = new Task();
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        task.setExecuteTime(wmNews.getPublishTime().getTime());//文章的发布时间
        /*WmNews taskNews = new WmNews();
        taskNews.setId(wmNews.getId());*/
        task.setParameters(ProtostuffUtil.serialize(wmNews));

        scheduleClient.addTask(task);
    }

    @Autowired
    @Lazy
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 拉取任务，审核文章
     */
//    @Scheduled(fixedRate = 1000)  //每秒钟拉取一次
    @Override
    public void pollTask() {

        /*ResponseResult responseResult = scheduleClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if(responseResult != null && responseResult.getCode().equals(200) && responseResult.getData() != null){
            //拿到任务对象
            Task task = JSON.parseObject(JSON.toJSONString(responseResult.getData()), Task.class);
            //审核文章
            byte[] parameters = task.getParameters();
            WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
            wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        }*/
        ResponseResult responseResult = scheduleClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if(responseResult != null && responseResult.getCode().equals(200) && responseResult.getData() != null){
            //拿到任务对象
            Task task = JSON.parseObject(JSON.toJSONString(responseResult.getData()), Task.class);
            //审核文章
            byte[] parameters = task.getParameters();
            WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
            //发布文章
            wmNewsAutoScanService.pubishNews(wmNews);
        }


    }
}
